/*
 * Copyright (c) 2024 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
#include "GPUDrawable.h"
#include "base/utils/Log.h"
#include "tgfx/opengl/egl/EGLWindow.h"
#include "hilog/log.h"

namespace pag {
const unsigned int LOG_DEBUG_DOMAIN = 0XFFF0;

std::shared_ptr<GPUDrawable> GPUDrawable::FromWindow(OH_NativeXComponent *component, void *nativeWindow,
    void *sharedContext) {
    if (nativeWindow == nullptr) {
        return nullptr;
    }
    return std::shared_ptr<GPUDrawable>(new GPUDrawable(component, nativeWindow, sharedContext));
}

GPUDrawable::GPUDrawable(OH_NativeXComponent *component, void *nativeWindow, void *sharedContext)
    : xComponent(component), nativeWindow(nativeWindow), sharedContext(sharedContext) {
    GPUDrawable::updateSize();
}

void GPUDrawable::updateSize() {
    if (nativeWindow != nullptr && xComponent != nullptr) {
        int32_t ret = OH_NativeXComponent_GetXComponentSize(xComponent, nativeWindow, (unsigned long *)&_width,
            (unsigned long *)&_height);
        OH_LOG_Print(LOG_APP, LOG_INFO, LOG_DEBUG_DOMAIN, "Prepare", "updateSize _width=%{public}d,\
            _height=%{public}d", _width, _height);
        if (ret != OH_NATIVEXCOMPONENT_RESULT_SUCCESS) {
            _width = 0;
            _height = 0;
        }
        if (window) {
            window->invalidSize();
        }
    }
}

    std::shared_ptr<tgfx::Device> GPUDrawable::getDevice() {
        if (_width <= 0 || _height <= 0) {
            return nullptr;
        }
        if (window == nullptr) {
            window = tgfx::EGLWindow::MakeFrom(reinterpret_cast<EGLNativeWindowType>(nativeWindow), sharedContext);
        }
        return window ? window->getDevice() : nullptr;
    }

std::shared_ptr<tgfx::Surface> GPUDrawable::onCreateSurface(tgfx::Context *context) {
    return window ? window->getSurface(context) : nullptr;
}

void GPUDrawable::onFreeSurface() {
    if (window) {
        window->freeSurface();
    }
}

void GPUDrawable::present(tgfx::Context *context) { window->present(context); }
} // namespace pag